<?php
namespace App\Services\Work;

use Illuminate\Support\Facades\DB;
use App\Models\System\User;
use App\Models\System\Term;
use App\Models\ActivityInfo;
use App\Models\Teachers;
use App\Models\DictionaryItem;
use App\Models\EventStatistics;
use App\Models\Participant;
use App\Models\FormInstance;
use App\Models\File;
use App\Models\SystemTask;
use App\Models\System\Tasks;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Excel\ExcelExport;

class WorkService{

    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
    }

    /**
     * 获取列表
     * @author lxy
     * @datetime 2023-02-28
     */
    public function getWorkList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];

        $user_id = auth()->user()->id;

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['level'])     && $where[] = ['activity_info.level','like','%'.$request['search']['level'].'%'];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        !empty($request['search']['teacher_name'])     && $where[] = ['activity_info.teacher_name','like','%'.$request['search']['teacher_name'].'%'];
        !empty($request['search']['status'])     && $where[] = ['b.status','=',$request['search']['status']];
        $level = !empty($request['search']['level'])?$request['search']['level']:'';

        //非管理员只能看到自己提交的数据
        // if(!is_check(184)){
        //     $where[] = ['activity_info.creator_id','=',$user_id];
        // }
        $where[] = ['activity_info.deleted','=',0];

        $where[] = ['activity_info.activity_category','=','IMPORTANTWORK_TEACHING_SITUATION_TABLE'];

        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.is_push',
            'activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade',
            'activity_info.category','activity_info.proof_material','b.status','c.participant','d.nickname',
            'activity_info.teacher_name','activity_info.school_name','activity_info.school_name','activity_info.creator_id')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.creator_id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
                ->where($where)
            ->manageable()
                ->when($level,function($q) use($level){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`level`,'$[0].optionId') = $level");
                })
                ->with('participants')
                ->when(!is_check(184),function($q) use($user_id){
                    return $q->whereHas('participants', function (Builder $query) use($user_id) {
                        $query->where('user_id', $user_id);
                    });
                })
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw("activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->orderBy('activity_info.created_at','desc')
                ->groupBy('activity_info.id')
                ->paginate($limit)
                ->toArray();

        $result['limit'] = $limit;

        return $result;
    }

    /**
     * 导出
     * @author lxy
     * @datetime 2023-02-24
     */
    public function exportWork($request)
    {
        $where = [];
        $user_id = auth()->user()->id;
        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        !empty($request['search']['level'])     && $where[] = ['activity_info.level','like','%'.$request['search']['level'].'%'];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        !empty($request['search']['teacher_name'])     && $where[] = ['activity_info.teacher_name','like','%'.$request['search']['teacher_name'].'%'];
        if(!empty($request['search']['status'])){
            $where[] = ['b.status','=',$request['search']['status']];
        }else{
            $where[] = ['b.status','=','PASS'];
        }
        $level = !empty($request['search']['level'])?$request['search']['level']:'';

        //非管理员只能看到自己提交的数据
        // if(!is_check(184)){
        //     $where[] = ['activity_info.creator_id','=',$user_id];
        // }
        $where[] = ['activity_info.deleted','=',0];

        $where[] = ['activity_info.activity_category','=','IMPORTANTWORK_TEACHING_SITUATION_TABLE'];

        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade','activity_info.category','b.status','c.participant','d.nickname','activity_info.teacher_name','activity_info.school_name')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
                ->where($where)
                ->when($level,function($q) use($level){
                    return $q->whereRaw(" JSON_EXTRACT(activity_info.`level`,'$[0].optionId') = $level");
                })
                ->with('participants')
                ->when(!is_check(184),function($q) use($user_id){
                    return $q->whereHas('participants', function (Builder $query) use($user_id) {
                        $query->where('user_id', $user_id);
                    });
                })
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw("activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->orderBy('activity_info.created_at','desc')
                ->get()
                ->toArray();

        $field_name = ['学年学期','活动名称','开始日期','结束日期','带教教师','所在学校','级别','状态','创建人'];
        $data = [];
        foreach($result as $k=>$v){
            $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['begin_date'];
            $data[$k][] = $v['end_date'];
            $data[$k][] = $v['participants_users']['user_str'];
            $data[$k][] = $v['school_name'];
            $data[$k][] = !empty($v['level_array'])?$v['level_array'][0]['selectValue']:'';
            $status = '';
            if($v['status'] == 'FILL_IN'){
                $status = '未提交';
            }else if($v['status'] == 'REVIEW'){
                $status = '待审核';
            }else if($v['status'] == 'REVIEW_FAIL'){
                $status = '已驳回';
            }else if($v['status'] == 'PASS'){
                $status = '审核通过';
            }
            $data[$k][] = $status;
            $data[$k][] = $v['nickname'];
        }
        array_unshift($data,$field_name);

        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }

    //带教情况
    public function getDjqkList($request)
    {
        $materials_array = explode(',',$request['materials_date']) ;
        $user_id = $request['user_id'];
        $limit = $request['limit'] ?? 10;
        //$username =  User::where('id',$user_id)->value('nickname');
        $result =  ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade','activity_info.category','activity_info.proof_material','b.status','c.participant','e.nickname','activity_info.teacher_name','activity_info.school_name')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('participant as d','activity_info.id','=','d.activity_info_id')
                ->leftJoin('users as e','activity_info.creator_id','=','e.id')
                ->where('activity_info.activity_category','IMPORTANTWORK_TEACHING_SITUATION_TABLE')
                ->where('b.status','PASS')
                ->whereIn('activity_info.data_version_id',$materials_array)
                ->where('activity_info.deleted', 0)
                //->whereRaw("(activity_info.teacher_name like '%{$username}%' or d.user_id={$user_id})")
                ->where('activity_info.creator_id',$user_id)
                ->orderBy('activity_info.created_at','desc')
                ->paginate($limit)
                ->toArray();
        $result['limit'] = $limit;

        return $result;
    }

    /**
     * 添加
     * @author lxy
     * @datetime 2023-02-27
     */
    public function addWork($request)
    {
        $id = !empty($request['id'])?$request['id']:0;
        $form_instance_id = !empty($request['form_instance_id'])?$request['form_instance_id']:0;
        $user_id = auth()->user()->id;
        $item = [];
        if(!empty($request['level'])) array_push($item,$request['level']);

        //学期名称
        $data_versions = Term::where('id',$request['data_version_id'])->first()->toArray();

        if($item){
            //获取旧字典
            $items = DictionaryItem::getDictionaryItem($item);
            $items = array_column($items,null,'optionId');
            if(!empty($request['level'])) $request['level'] = json_encode([$items[$request['level']]]);
        }


        //文件
        $files = !empty($request['files'])?[$request['files']]:'';
        //参与教师
        $participant = !empty($request['participant'])?$request['participant']:'';
        $participant_id = !empty($request['participant_id'])?$request['participant_id']:'';
        $status = $request['status'] == 1?'REVIEW':'FILL_IN';
        unset($request['files'],$request['file'],$request['participant'],$request['participant_id'],$request['id'],$request['status']);
        if(empty($request['begin_date'])) unset($request['begin_date']);
        if(empty($request['end_date'])) unset($request['end_date']);

        //已经提交过的数据不能保存
        if($status == 'FILL_IN'){
            if($id){
                $fi_status = FormInstance::where('id',$form_instance_id)->value('status');
                if($fi_status != 'FILL_IN'){
                    throw new \Exception('已提交过的数据不能继续保存');
                }
            }
        }

        try{
            DB::beginTransaction();
            $filesArr = [];
            //文件附件
            if($files){
                $proof_material = $this->activityRepository->dealUploadFile($files);
                $filesArr = array_column(json_decode($files[0],true)?:[], 'files_id');
            }
            $activity   =   '';
            //添加
            if(!$id){
                //审核
                $formInstance = FormInstance::create([
                    'form_key'=>'IMPORTANTWORK_TEACHING_SITUATION_OPERATION',
                    'type'=>'ActivityCreate',
                    'owner_id'=>$user_id,
                    'status'=>$status,
                   // 'display_mode'=>$status == 'REVIEW'?'REVIEW':'EDIT',
                    'data_version_id'=>$request['data_version_id'],
                    'data_version_name'=>$data_versions['title'],
                    'creator_id'=>$user_id,
                ]);

                $request['creator_id'] = $user_id;
                $request['activity_category'] = 'IMPORTANTWORK_TEACHING_SITUATION_TABLE';
                $request['proof_material'] = $files?json_encode($proof_material):'';
                $request['form_instance_id'] = $formInstance->id;
                $activity = ActivityInfo::create(array_filter($request));
                $id = $activity->id;

            }else{  //编辑
                $formInstance = FormInstance::where('id',$form_instance_id)->first();

                if($formInstance->status == 'FILL_IN' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }else if($formInstance->status  == 'REVIEW_FAIL' && $status == 'REVIEW'){
                    FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                }

                if($files){
                    $request['proof_material'] = $files?json_encode($proof_material):'';
                }
                $request['updater_id'] = $user_id;

                FormInstance::where('id',$form_instance_id)->update(['data_version_id'=>$request['data_version_id'],'data_version_name'=>$data_versions['title']]);
                ActivityInfo::where('id',$id)->update(array_filter($request));

            }

            //添加待办事项
            if($status=='REVIEW'){
                //处理有驳回的数据
                Tasks::where('form_key','IMPORTANTWORK_TEACHING_SITUATION_OPERATION')->where('form_id',$id)->where('status',1)->where('type',3)->update(['status'=>2]);
                if(!Tasks::where('form_key','IMPORTANTWORK_TEACHING_SITUATION_OPERATION')->where('form_id',$id)->where('status',1)->first()){
                    Tasks::create([
                        'name'=>'【'.$data_versions['title'].'】重要工作-带教情况审核',
                        'data_version_id'=>$request['data_version_id'],
                        'form_id'=>$id,
                        'form_key'=>'IMPORTANTWORK_TEACHING_SITUATION_OPERATION',
                        'start_date'=>date('Y-m-d H:i:s'),
                        'end_date'=>$request['end_date'],
                        'creator_id'=>$user_id,
                        'creator_name'=>auth()->user()->nickname,
                        'param'=>'?id='.$id,
                        'url'=>'/work/work/check',
                        'menu_id'=>184
                    ]);
                }
            }

           //参与人员
           if($participant){
                EventStatistics::updateOrCreate(
                    ['activity_info_id' => $id],
                    [
                    'type' => '带教情况',
                    'child_type' => '带教情况',
                    'name' => !empty($request['name'])?$request['name']:'',
                    'level' => !empty($request['level'])?json_decode($request['level'],true)[0]['selectValue']:'',
                    'participant' => $participant,
                    'date' => date('Y-m-d'),
                    'data_version_id' => $request['data_version_id'],
                ]);

                $data = [];
                Participant::where('activity_info_id',$id)->delete();
                foreach($participant_id as $k=>$v){
                    $data[$k]['created_at'] = date('Y-m-d H:i:s');
                    $data[$k]['creator_id'] = $user_id;
                    $data[$k]['updated_at'] = date('Y-m-d H:i:s');
                    $data[$k]['updater_id'] = $user_id;
                    $data[$k]['activity_info_id'] = $id;
                    $data[$k]['activity_category'] = 'IMPORTANTWORK_TEACHING_SITUATION_TABLE';
                    $data[$k]['user_id'] = $v;
                    $data[$k]['participant_type'] = 'PARTICIPANT';
                    $data[$k]['name'] = !empty($request['name'])?$request['name']:'';
                }
                Participant::insert($data);
            }

            //关联推优文件处理
            if (!empty($filesArr)){
                $activity = $activity?:ActivityInfo::find($id);
                $activity->files_id = $filesArr;
            }
            DB::commit();
            return $id;

        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 审核
     * @author lxy
     * @datetime 2023-02-24
     */
    public function checkWork($request)
    {
        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $result = FormInstance::where('id',$request['form_instance_id'])->update([
            'status'=>$request['status'],
            'comment'=>$request['comment'],
            'updater_id'=>auth()->user()->id,
        ]);

        //修改待办事项
        Tasks::where('form_key','IMPORTANTWORK_TEACHING_SITUATION_OPERATION')->where('form_id',$request['id'])->update(['status'=>2]);

        //如果是驳回，重新给申报人发起待办事项
        if($request['status']== 'REVIEW_FAIL'){
            $task = Tasks::where('form_key','IMPORTANTWORK_TEACHING_SITUATION_OPERATION')->where('form_id',$request['id'])->where('type',1)->orderBy('created_at','desc')->first();
            if(!$task){
                return [];
            }
            $task = $task->toArray();
            Tasks::create([
                'name'=>$task['name'].'驳回',
                'type' => 3,
                'data_version_id'=>$task['data_version_id'],
                'form_id'=>$task['form_id'],
                'form_key'=>'IMPORTANTWORK_TEACHING_SITUATION_OPERATION',
                'start_date'=>date('Y-m-d H:i:s'),
                'end_date'=>$task['end_date'],
                'c_user_id' => $task['creator_id'],
                'c_user_name' => $task['creator_name'],
                'creator_id'=>auth()->user()->id,
                'creator_name'=>auth()->user()->nickname,
                'param'=>$task['param'],
                'url'=>'/work/work/add',
                'menu_id'=>182
            ]);
        }

        return $result;
    }

    /**
     * 删除
     * @author lxy
     * @datetime 2023-03-07
     */
    public function delWork($request)
    {
        $id = $request['id'];
        Tasks::where('form_key','IMPORTANTWORK_TEACHING_SITUATION_OPERATION')->where('form_id',$id)->where('status',1)->delete();
        return ActivityInfo::where('id',$id)->update(['deleted'=>1]);
    }

}

?>
